<?php
/**
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/11/7 16:10
 */
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
include_once dirname(__FILE__)."/soap/client.php";
\ns_core\m_load::load("ns_model.delivery.cdn_delivery_explain");
class delivery extends \ns_model\delivery\cdn_delivery_explain
{
    /**
     * CDN注入统一解释器入口
     */
    public function explain()
    {
        $fuc_name = (string)$this->get_c2_type();
        if (empty($fuc_name))
        {
            return $this->write_log_return('C2类型参数为空', NS_CDS_FAIL);
        }
        return $this->save_exec_log($this->$fuc_name());
    }

    /**
     * CDN注入统一发送器入口
     * 按项目进行自定义发送处理
     * @param $data array(
     *       'nns_task_type' =>类型,
     *       'nns_action' => 行为动作，
     *       'nns_content' => 注入XML内容
     * );
     * @return array('ret','reason');
     */
    public function execute($data)
    {
        $cdn_code = NS_CDS_CDN_LOADING;
        //生成CDN工单唯一ID
        $data['nns_id'] = $this->get_guid();
//        $task = $this->save_execute_import_content($data['nns_content'], $this->arr_sp_config['xml_ftp']);
        $task = \m_config::write_execute_cdn_import_content($this->str_sp_id,$this->get_c2_type(),$this->get_c2_info('action'),$data['nns_content']);
        if ($task['ret'] != 0)
        {
            $this->write_log_return($task['reason'], NS_CDS_FAIL);
            return $task;
        }
//        $local_url = $task['data_info']['base_dir'];
//        $ftp_url = $task['data_info']['ftp_url'];
        $local_url = $task['data_info']['base_dir'];
        $ftp_url = $this->arr_sp_config['xml_ftp'].$task['data_info']['base_dir'];
        $wsdl_url = "http://10.20.200.59/bk/nn_cds/v2/ns_api/hlj/delivery/hljdx_hw/soap/service.php?wsdl";
        try
        {
            $client_re = client::ExecCmd($data['nns_id'], $ftp_url,$wsdl_url);
            $import_code = isset($client_re->Result) ? $client_re->Result : $client_re->result;
            $import_code = ($import_code === null) ? NS_CDS_CDN_NOTIFY_SUCCE : $import_code;
            $reason = $client_re->ErrorDescription;
            if ($import_code != NS_CDS_CDN_NOTIFY_SUCCE)
            {
                $cdn_code = NS_CDS_CDN_FAIL;
                $reason = '发送cdn失败' . $reason;
            }
            $this->write_log_return($reason, $cdn_code);
        } catch (Exception $e)
        {
            $import_code = NS_CDS_CDN_FAIL;
            $cdn_code = NS_CDS_CDN_FAIL;
            $reason = '抛出异常,发送CDN失败,请联系工作人员';
            $this->write_log_return($reason, $cdn_code);
        }

        $data['nns_url'] = $local_url;
        $data['nns_result'] = $import_code;
        $data['nns_send_time'] = date("Y-m-d H:i:s");
        $data['nns_result_fail_reason'] = $reason;
        $data['nns_task_id'] = $this->get_c2_info('id');
        $data['nns_task_name'] = $this->get_c2_info('name');
        //兼容直播打包注入
        if (isset($this->arr_sp_config['playbill']['enabled'])
            && $this->arr_sp_config['playbill']['enabled'] && $data['nns_task_type'] == 'Schedule')
        {
            $playbill_info = $this->get_playbill_info();
            $task_id_arr = array();
            foreach ($playbill_info as $item)
            {
                if(!empty($item['c2_task_id']))
                {
                    $task_id_arr[] = $item['c2_task_id'];
                }
            }
            if(!empty($task_id_arr))
            {
                $data['nns_ex_group'] = json_encode($task_id_arr);
                $this->c2_info['task_ex_group'] = json_encode($task_id_arr);
            }
        }
        /**
         * $data
         * array(
         *            'nns_task_type'=>'Series',
         *            'nns_task_id'=> 'C2任務ID',
         *            'nns_task_name'=> '任務名稱',
         *            'nns_action'=> '行為動作',
         *            'nns_result' => 0 成功 其他失敗
         *            'nns_result_fail_reason' => 發送失敗原因描述
         *      )
         * */
        $build_c2 = $this->build_c2_log($data);
        if($build_c2['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($build_c2['reason'], $build_c2['ret']);
        }
        return $this->is_ok($cdn_code, $reason);
    }

    /**
     * @description:调用进行反馈
     * @author:xinxin.deng
     * @date: 2018/3/6 11:33
     * @param $c2_correlate_id
     * @param $code
     * @param $result_url
     * @return array
     */
    public function notify($c2_correlate_id, $code, $result_url)
    {
        //$reason = '注入CDN成功';
        $notify_result = 'CDN反馈成功';
        if (!empty($result_url))
        {
            //获取到xml内容
            //$notify_result = @file_get_contents($result_url);
            $notify = $this->save_ftp_content($result_url);
            $this->write_log_return('获取到的数据为:' . var_export($notify), true);
            if (!$notify)
            {
                $reason = '发送至CDN成功,但是下载CDN反馈的远程文件失败' . $result_url;
                $notify_result = 'CDN反馈成功但是,' . $reason;
                $this->write_log_return('下载CDN反馈的远程文件失败' . $result_url, NS_CDS_FAIL);
            }
            else
            {
                //解析得到xml反馈的原因
                $ar_result = $this->notify_content_to_arr($notify);
                $this->write_log_return('解析到的数据为:' . var_export($ar_result), true);
                if ($ar_result['ret'] != 0)
                {
                    $reason = '发送至CDN成功但是,' . $ar_result['reason'];
                    $notify_result = 'CDN反馈成功但是,' . $ar_result['reason'];
                    $this->write_log_return($ar_result['reason'], NS_CDS_FAIL);
                } else
                {
                    if ($ar_result['data_info']['Result'] != 0)
                    {
                        $reason = '发送至CDN成功,但注入失败,反馈消息为：' . $ar_result['data_info']['Description'];
                        $notify_result = 'CDN反馈成功但是,注入失败,反馈消息为:' . $ar_result['data_info']['Description'];
                        $this->write_log_return($reason, NS_CDS_FAIL);
                    }
                }
            }
        }
        return $this->is_notify_ok($c2_correlate_id, $code, $notify_result, $notify);
    }

    /**
     * 主媒资注入CDN
     * @return array
     */
    private function video()
    {
        $action = $this->get_c2_info("action");
        if ($action === NS_CDS_DELETE)
        {
            return $this->do_destroy("DELETE", "video");
        }
        if ($action === NS_CDS_MODIFY)
        {
            $action = "UPDATE";
        }
        else
        {
            $action = "REGIST";
        }
        $video_info = $this->get_video_info();
        if (empty($video_info))
        {
            return $this->write_log_return("C2任务video数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        /*******获取CDN注入ID******/
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("主媒资C2任务生成CDN注入ID失败", NS_CDS_FAIL);
        }
        $current_time = date('YmdHis');
        $xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
        $xml_str .= '<Objects>';
        $xml_str .= '<Object ElementType="Series" ID="' . $cdn_import_id . '" Action="' . $action . '" Code="' . $cdn_import_id . '">';
        $xml_str .= '<Property Name="Name">' . htmlspecialchars($video_info['base_info']['nns_name'], ENT_QUOTES) . '</Property>';
        $xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
        $xml_str .= '<Property Name="OriginalName">' . htmlspecialchars($video_info['nns_alias_name'], ENT_QUOTES) . '</Property>';//原名
        $xml_str .= '<Property Name="SortName"></Property>';//索引名称供界面排序
        $xml_str .= '<Property Name="SearchName">' . htmlspecialchars($video_info['base_info']['nns_pinyin'], ENT_QUOTES) . '</Property>';//搜索名称供界面搜索
        $str_date = ($video_info['base_info']['nns_show_time'] == '0000-00-00' || empty($video_info['base_info']['nns_show_time'])) ? date('Ymd') : date('Ymd', strtotime($video_info['base_info']['nns_show_time']));
        $xml_str .= '<Property Name="OrgAirDate">' . $str_date . '</Property>';//首播日期(YYYYMMDD)
        $xml_str .= '<Property Name="LicensingWindowStart">'.$current_time.'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
        $xml_str .= '<Property Name="LicensingWindowEnd">20991225235959</Property>';//有效结束时间(YYYYMMDDHH24MiSS)
        $xml_str .= '<Property Name="DisplayAsNew">0</Property>';//新到天数
        $xml_str .= '<Property Name="DisplayAsLastChance">999</Property>';//剩余天数
        $xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护	1:有拷贝保护
        $xml_str .= '<Property Name="Price">0</Property>';//含税定价
        $xml_str .= '<Property Name="VolumnCount">' . $video_info['base_info']['nns_all_index'] . '</Property>';//总集数
        $xml_str .= '<Property Name="Status">1</Property>';//状态标志,0:失效 1:生效
        $xml_str .= '<Property Name="Description">' . htmlspecialchars(mb_substr($video_info['base_info']['nns_summary'], 0, 128, 'utf-8'), ENT_QUOTES) . '</Property>';//描述信息
        $xml_str .= '<Property Name="Type">' . htmlspecialchars($video_info['base_info']['nns_kind'], ENT_QUOTES) . '</Property>';//节目内容类型,字符串，表示内容类型，例如：电影，连续剧，新闻，体育…
        $xml_str .= '<Property Name="Keywords">' . htmlspecialchars(mb_substr($video_info['base_info']['nns_keyword'], 0, 32, 'utf-8'), ENT_QUOTES) . '</Property>';//关键字
        $xml_str .= '<Property Name="Tags">0</Property>';//关联标签
//        $xml_str .= '<Property Name="Reserve1"></Property>';//保留字段
//        $xml_str .= '<Property Name="Reserve2"></Property>';//保留字段
//        $xml_str .= '<Property Name="Reserve3"></Property>';//保留字段
//        $xml_str .= '<Property Name="Reserve4"></Property>';//保留字段
//        $xml_str .= '<Property Name="Reserve5"></Property>';//保留字段
        $xml_str .= '</Object>';
        $xml_str .= '</Objects>';
        $xml_str .= '</ADI>';
        /*******调用统一注入方法******/
        $execute_info = array(
            'nns_task_type' => "Series",//媒资类型
//            'nns_task_type' => "video",//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml_str,//注入XML内容
        );
        return $this->execute($execute_info);
    }

    /**
     * 分集注入CDN
     * @return array
     */
    private function index()
    {
        $action = $this->get_c2_info('action');
        if ($action === NS_CDS_DELETE)
        {
            return $this->do_destroy("DELETE", "index");
        }
        if ($action === NS_CDS_MODIFY)
        {
            $action = "UPDATE";
        } else
        {
            $action = "REGIST";
        }
        $index_info = $this->get_index_info();
        if (empty($index_info))
        {
            return $this->write_log_return("C2任务index数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        /*******获取分集CDN注入ID******/
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("分集C2任务生成CDN注入ID失败", NS_CDS_FAIL);
        }
        $xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
        $xml_str .= '<Objects>';
        $xml_str .= '<Object ElementType="Program" ID="' . $cdn_import_id . '" Action="' . $action . '" Code="' . $cdn_import_id . '">';
        $xml_str .= '<Property Name="Name">' . htmlspecialchars($index_info['base_info']['nns_name'], ENT_QUOTES) . '</Property>';
        $xml_str .= '<Property Name="OrderNumber"></Property>';//节目订购编号
        $xml_str .= '<Property Name="OriginalName">' . htmlspecialchars($index_info['base']['nns_alias_name'], ENT_QUOTES) . '</Property>';//原名
        $xml_str .= '<Property Name="SortName"></Property>';//索引名称供界面排序
        $xml_str .= '<Property Name="SearchName">' . htmlspecialchars($index_info['base_info']['nns_pinyin'], ENT_QUOTES) . '</Property>';//搜索名称供界面搜索
        $xml_str .= '<Property Name="Genre">Genre</Property>';//Program的默认类别（Genre）

        $actor = isset($index_info['base_info']['nns_actor']) ? $index_info['base_info']['nns_actor'] : '未知';
        $writer = isset($index_info['base_info']['nns_director']) ? $index_info['base_info']['nns_director'] : '未知';
        $xml_str .= '<Property Name="ActorDisplay">' . htmlspecialchars(mb_substr($actor, 0, 32, 'utf-8'), ENT_QUOTES) . '</Property>';//演员
        $xml_str .= '<Property Name="WriterDisplay">' . htmlspecialchars(mb_substr($writer, 0, 32, 'utf-8'), ENT_QUOTES) . '</Property>';//导演
        $xml_str .= '<Property Name="OriginalCountry">' . htmlspecialchars(mb_substr($index_info['base_info']['nns_area'], 0, 32, 'utf-8'), ENT_QUOTES) . '</Property>';//上映国家
        $xml_str .= '<Property Name="Language">' . htmlspecialchars(mb_substr($index_info['base_info']['nns_language'], 0, 32, 'utf-8'), ENT_QUOTES) . '</Property>';//语言

        $str_date = ($index_info['base_info']['nns_show_time'] == '0000-00-00' || empty($index_info['base_info']['nns_show_time'])) ? date('Ymd') : date('Ymd', strtotime($index_info['base_info']['nns_show_time']));
        $current_time = date('YmdHis');
        $xml_str .= '<Property Name="ReleaseYear">' . date('Y', strtotime($str_date)) . '</Property>';//上映时间
        $xml_str .= '<Property Name="OrgAirDate">' . $str_date . '</Property>';//首播日期(YYYYMMDD)
        $xml_str .= '<Property Name="LicensingWindowStart">'.$current_time.'</Property>';//有效开始时间(YYYYMMDDHH24MiSS)
        $xml_str .= '<Property Name="LicensingWindowEnd">20991225235959</Property>';//有效结束时间(YYYYMMDDHH24MiSS)
        $xml_str .= '<Property Name="DisplayAsNew">0</Property>';//新到天数
        $xml_str .= '<Property Name="DisplayAsLastChance">300</Property>';//剩余天数
        $xml_str .= '<Property Name="Macrovision">0</Property>';//拷贝保护标志0:无拷贝保护	1:有拷贝保护
        $xml_str .= '<Property Name="Description">' . htmlspecialchars(mb_substr($index_info['base_info']['nns_summary'], 0, 128, 'utf-8'), ENT_QUOTES) . '</Property>';//描述信息
        $xml_str .= '<Property Name="PriceTaxIn">0</Property>';//列表定价
        $xml_str .= '<Property Name="Status">1</Property>';//状态标志,0:失效 1:生效
        $xml_str .= '<Property Name="SourceType">1</Property>';//状态标志,0:失效 1:生效
        $xml_str .= '<Property Name="SeriesFlag">0</Property>';//0: 电影 1: 连续剧剧集

        if (empty($index_info['base_info']['nns_kind']))
        {
            $index_info['base_info']['nns_kind'] = $index_info['base_info']['nns_keyword'];
        }
        $xml_str .= '<Property Name="Type">' . htmlspecialchars($index_info['base_info']['nns_kind'], ENT_QUOTES) . '</Property>';//节目内容类型,字符串，表示内容类型，例如：电影，连续剧，新闻，体育…
        $xml_str .= '<Property Name="Keywords">' . htmlspecialchars(mb_substr($index_info['base_info']['nns_keyword'], 0, 32, 'utf-8'), ENT_QUOTES) . '</Property>';//关键字
        $xml_str .= '<Property Name="Tags">1</Property>';//关联标签
//        $xml_str .= '<Property Name="Reserve1"></Property>';//保留字段
//        $xml_str .= '<Property Name="Reserve2"></Property>';//保留字段
//        $xml_str .= '<Property Name="Reserve3"></Property>';//保留字段
//        $xml_str .= '<Property Name="Reserve4"></Property>';//保留字段
//        $xml_str .= '<Property Name="Reserve5"></Property>';//保留字段
        $xml_str .= '</Object>';
        $xml_str .= '</Objects>';

        $xml_str .= '<Mappings>';

        if ($action == "REGIST")
        {
            $sequence = $index_info['base_info']['nns_index'] + 1;
            if ($sequence > 999)
            {
                $sequence = 999;
            }
            /*******获取主媒资CDN注入ID******/
            $cdn_video_import_id = $this->get_video_cdn_import_id(NS_CDS_VIDEO);
            if (empty($cdn_video_import_id))
            {
                return $this->write_log_return("分集C2任务生成主媒资CDN注入ID失败", NS_CDS_FAIL);
            }
            $xml_str .= '<Mapping ParentType="Series" ParentID="' . $cdn_video_import_id . '" ElementType="Program" ElementID="' . $cdn_import_id . '" ParentCode="' . $cdn_video_import_id . '" ElementCode="' . $cdn_import_id . '" Action="' . $action . '">';
            $xml_str .= '<Property Name="Sequence">' . $sequence . '</Property>';
            $xml_str .= '</Mapping>';
            /*/图片
            if(!empty($vod_info['nns_image'])){
                $xml_str .= '<Mapping ParentType="Picture" ParentID="'.$program_id.'_index_image'.'" ElementType="Program" ElementID="'.$program_id.'" ParentCode="'.$program_id.'_index_image'.'" ElementCode="'.$program_id.'" Action="' . $action . '">';
                //Picture时：0: 缩略图 1: 海报 2: 剧照 3: 图标 4: 标题图 5: 广告图 6: 草图 7: 背景图 9: 频道图片
                //10: 频道黑白图片 11: 频道Logo 12: 频道名字图片99: 其他
                $xml_str .= '<Property Name="Type">1</Property>';
                $xml_str .= '<Property Name="Sequence">0</Property>';//
                $xml_str .= '</Mapping>';
            }*/
        }
        $xml_str .= '</Mappings>';
        $xml_str .= '</ADI>';
        /*******调用统一注入方法******/
        $execute_info = array(
            'nns_task_type' => "Program",//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml_str,//注入XML内容
        );
        return $this->execute($execute_info);
    }

    /**
     * 片源注入CDN
     * @return array
     */
    private function media()
    {
        if ($this->get_c2_info("action") === NS_CDS_DELETE)
        {
            return $this->do_destroy("DELETE", "media");
        } else
        {
            $action = "REGIST";
        }
        $media_info = $this->get_media_info();
        if (empty($media_info))
        {
            return $this->write_log_return("C2任务media数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }

        /*******获取CDN注入ID******/
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("片源C2任务生成CDN注入ID失败", NS_CDS_FAIL);
        }

        $ar_sp_config = $this->arr_sp_config;
        $url = $ar_sp_config['media_ftp'] . $this->get_c2_info("file_path");

        $xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
        $xml_str .= '<Objects>';
        $xml_str .= '<Object ElementType="Movie" ID="' . $cdn_import_id . '" Action="' . $action . '" Code="' . $cdn_import_id . '" >';
        $xml_str .= '<Property Name="Type">1</Property>';//媒体类型1:正片 2:预览片
        $xml_str .= '<Property Name="FileURL">' . $url . '</Property>';//媒体文件URL,ftp://username:password@ip:port/...  标准FTP协议
        $xml_str .= '<Property Name="SourceDRMType">1</Property>';//0: No DRM 1: BES DRM
        $xml_str .= '<Property Name="DestDRMType">1</Property>';//
        $xml_str .= '<Property Name="AudioType">1</Property>';//0: 其他 1: Monaural 单声道 2: Stereo 多声道 3: Two-nation monaural 双单声道 4: Two-nation stereo 双多声道  5: AC3(5:1 channel) AC3声道
        $xml_str .= '<Property Name="ClosedCaptioning">1</Property>';//0:无字幕 1:有字幕
        $xml_str .= '</Object>';
        $xml_str .= '</Objects>';
        $xml_str .= '<Mappings>';

        /*******获取分集CDN注入ID******/
        $cdn_index_import_id = $this->get_video_cdn_import_id(NS_CDS_INDEX);
        if (empty($cdn_index_import_id))
        {
            return $this->write_log_return("片源C2任务生成父级分集CDN注入ID失败", NS_CDS_FAIL);
        }

        $xml_str .= '<Mapping ParentType="Program" ParentID="' . $cdn_index_import_id . '" ElementType="Movie" ElementID="' . $cdn_import_id . '" ParentCode="' . $cdn_index_import_id . '" ElementCode="' . $cdn_import_id . '" Action="' . $action . '">';
        $xml_str .= '</Mapping>';
        $xml_str .= '</Mappings>';
        $xml_str .= '</ADI>';
        /*******调用统一注入方法******/
        $execute_info = array(
            'nns_task_type' => "Movie",
            'nns_action' => $action, //行为动作
            'nns_content' => $xml_str,//注入XML内容
        );
        return $this->execute($execute_info);
    }

    /**
     * 直播频道注入CDN
     * @return array
     */
    private function live()
    {
        $action = $this->get_c2_info("action");
        if ($action === NS_CDS_DELETE)
        {
            return $this->do_destroy("DELETE", "live");
        }
        if ($action === NS_CDS_MODIFY)
        {
            $action = "UPDATE";
        }
        else
        {
            $action = "REGIST";
        }
        $live_info = $this->get_live_info();
        if (empty($live_info))
        {
            return $this->write_log_return("C2任务video数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        /*******获取CDN注入ID******/
        $cdn_import_id = $this->get_video_cdn_import_id("live");
        //获取该频道下直播源
        $live_media_info = nl_live_media::query_by_condition(\m_config::get_dc(),array("nns_live_id"=>$live_info['base_info']['nns_id'],'nns_deleted'=>0));
        $live_media_info = $live_media_info['data_info']['0'];
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("主媒资C2任务生成CDN注入ID失败", NS_CDS_FAIL);
        }
        if(!is_array($live_media_info) && empty($live_media_info))
        {
            return $this->write_log_return("直播频道下无直播源", NS_CDS_FAIL);
        }
        //计算组播地址和端口
        $live_media_url = $live_media_info['nns_url'];
        $arr_live_media_url = explode(':',$live_media_url);
        $m_queue_model = new \ns_model\m_queue_model();
        $temp_live_media_info['live_media']['base_info'] = $live_media_info;
        $arr_live_media_import_info = $m_queue_model->_get_cdn_epg_import_id($this->str_sp_id,"live_media",$temp_live_media_info);
        //计算频道号
        $channel_number = 999;
        $live_ex_info = nl_live::query_ex_by_id(m_config::get_dc(),$live_info['base_info']['nns_id']);
        if($live_ex_info['ret'] != 0 || !is_array($live_ex_info['data_info']) || empty($live_ex_info['data_info']))
        {
            return $this->write_log_return("获取直播频道扩展信息失败", NS_CDS_FAIL);
        }
        foreach ($live_ex_info['data_info'] as $value)
        {
            if($value['nns_key'] == 'live_pindao_order')
            {
                $channel_number= $value['nns_value'];
            }
        }
        $xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
        $xml_str .= '<Objects>';
        $xml_str .= '<Object ElementType="Channel" ID="' . $cdn_import_id . '" Action="'.$action.'" Code="' . $cdn_import_id . '">';
        $xml_str .= '<Property Name="Name">' . htmlspecialchars($live_info['base_info']['nns_name'], ENT_QUOTES) . '</Property>';
        $xml_str .= '<Property Name="ChannelNumber">'.$channel_number.'</Property>';//频道号
        $xml_str .= '<Property Name="StartTime">0000</Property>';//频道类型
        $xml_str .= '<Property Name="EndTime">2359</Property>';//频道类型
        $xml_str .= '<Property Name="Type">1</Property>';//频道类型
        $xml_str .= '<Property Name="Status">1</Property>';//状态标志,0:失效 1:生效
        $xml_str .= '</Object>';
        //下面拼接直播源地址
        $xml_str .= '<Object ElementType="PhysicalChannel" ID="' . $arr_live_media_import_info['data_info'] . '" Action="'.$action.'" Code="' . $arr_live_media_import_info['data_info'] . '">';
        $xml_str .= '<Property Name="ChannelCode">' . $cdn_import_id . '</Property>';
        $xml_str .= '<Property Name="BitRateType">6</Property>';       //媒体码率描述符
        $xml_str .= '<Property Name="MultiCastIP">'.$arr_live_media_url['0'].'</Property>';       //组播地址
        $xml_str .= '<Property Name="MultiCastPort">'.$arr_live_media_url['1'].'</Property>';     //组播端口
        $xml_str .= '</Object>';
        $xml_str .= '</Objects>';
        $xml_str .= '</ADI>';
        /*******调用统一注入方法******/
        $execute_info = array(
            'nns_task_type' => "Channel",//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml_str,//注入XML内容
        );
        return $this->execute($execute_info);
    }

    /**
     * 节目单注入
     * @return array
     */
    private function playbill()
    {
        //1、CDN注入前奏，获取节目单信息，
        if ($this->get_c2_info("action") === NS_CDS_DELETE)
        {
            return  $this->playbill_destroy();
        }
        else
        {
            $action = "REGIST";
        }
        //2、找到直播频道、频道注入ID、节目单详情
        $live_import_id = $this->get_video_cdn_import_id('live');
        $playbill_info = $this->get_playbill_info();
        //3、获取工单中BizDomain节点
        $int_bizdomain = $this->get_BizDomain($this->str_sp_id);
        //4、工单拼接
        $str_xml  ='<?xml version="1.0" encoding="UTF-8"?>';
        $str_xml .='<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$int_bizdomain.'" Priority="1">';
        $str_xml .=   '<Objects>';
        if (isset($this->arr_sp_config['playbill']['enabled']) && $this->arr_sp_config['playbill']['enabled'])
        {
            foreach ($playbill_info as $playbill_value)
            {
                //根据项目定制化设置获取的节目但注入id等
                $int_begin_time = strtotime($playbill_value['nns_begin_time']);
                $str_start_date = date('Ymd', $int_begin_time);
                $str_start_time = date('His', $int_begin_time);
                $str_duration = str_pad($playbill_value['nns_time_len'],6,0,STR_PAD_LEFT);
                $temp_playbill_value['base_info'] =  $playbill_value;
                $playbill_import_id = $this->get_video_cdn_import_id($this->get_c2_type(), $temp_playbill_value);
                $str_xml .='<Object ElementType="Schedule" ID="' . $playbill_import_id . '" Action="'. $action . '" Code="' . $playbill_import_id . '">';
                $str_xml .=   '<Property Name="ChannelCode">' . $live_import_id . '</Property>';
                $str_xml .=   '<Property Name="ChannelID">' . $live_import_id . '</Property>';
                $str_xml .=   '<Property Name="ProgramName"><![CDATA['.$playbill_value['nns_name'].']]></Property>';
                $str_xml .=   '<Property Name="StartDate">'.$str_start_date.'</Property>';
                $str_xml .=   '<Property Name="StartTime">' . $str_start_time . '</Property>';
                $str_xml .=   '<Property Name="Duration">' . $str_duration . '</Property>';
                $str_xml .=   '<Property Name="StorageDuration"></Property>';
                $str_xml .=   '<Property Name="Status">1</Property>';
                $str_xml .=   '<Property Name="CPContentID">'.$live_import_id.'</Property>';
                $str_xml .=    '<Property Name="Description"><![CDATA['.$playbill_value['nns_summary'].']]></Property>';
                $str_xml .=   '<Property Name="Genre"></Property>';
                $str_xml .='</Object>';
            }
        }
        else
        {
            $int_begin_time = strtotime($playbill_info['base_info']['nns_begin_time']);
            $str_start_date = date('Ymd', $int_begin_time);
            $str_start_time = date('His', $int_begin_time);
            $str_duration = str_pad($playbill_info['base_info']['nns_time_len'],6,0,STR_PAD_LEFT);
            $playbill_import_id = $this->get_video_cdn_import_id($this->get_c2_type(), $playbill_info);
            $str_xml .='<Object ElementType="Schedule" ID="' . $playbill_import_id . '" Action="'. $action . '" Code="' . $playbill_import_id . '">';
            $str_xml .=   '<Property Name="ChannelCode">' . $live_import_id . '</Property>';
            $str_xml .=   '<Property Name="ChannelID">' . $live_import_id . '</Property>';
            $str_xml .=   '<Property Name="ProgramName"><![CDATA['.$playbill_info['base_info']['nns_name'].']]></Property>';
            $str_xml .=   '<Property Name="StartDate">'.$str_start_date.'</Property>';
            $str_xml .=   '<Property Name="StartTime">' . $str_start_time . '</Property>';
            $str_xml .=   '<Property Name="Duration">' . $str_duration . '</Property>';
            $str_xml .=   '<Property Name="StorageDuration"></Property>';
            $str_xml .=   '<Property Name="Status">1</Property>';
            $str_xml .=   '<Property Name="CPContentID">'.$live_import_id.'</Property>';
            $str_xml .=    '<Property Name="Description"><![CDATA['.$playbill_info['base_info']['nns_summary'].']]></Property>';
            $str_xml .=   '<Property Name="Genre"></Property>';
            $str_xml .='</Object>';
        }
        $str_xml .=   '</Objects>';
        $str_xml .='</ADI>';
        /*******调用统一注入方法******/
        $execute_info = array(
            'nns_task_type' => "Schedule",
            'nns_action' => $action, //行为动作
            'nns_content' => $str_xml,//注入XML内容
        );
        return $this->execute($execute_info);
    }

    /**
     * 节目单删除
     * @return array
     */
    private function playbill_destroy()
    {
        $action = 'DELETE';
        //2、找到直播频道、节目单详情
        $playbill_info = $this->get_playbill_info();
        $live_info = $this->get_live_info();
        $live_import_id = $this->get_video_cdn_import_id('live');
        $int_bizdomain = $this->get_BizDomain($this->str_sp_id);
        $str_xml  ='<?xml version="1.0" encoding="UTF-8"?>';
        $str_xml .='<ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="'.$int_bizdomain.'" Priority="1">';
        $str_xml .=   '<Objects>';
        if (isset($this->arr_sp_config['playbill']['enabled']) && $this->arr_sp_config['playbill']['enabled'] && empty($playbill_info['base_info']))
        {
            foreach ($playbill_info as $playbill_value)
            {
                //根据项目定制化设置获取的节目但注入id等
                $int_begin_time = strtotime($playbill_value['nns_begin_time']);
                $str_start_date = date('Ymd', $int_begin_time);
                $str_start_time = date('His', $int_begin_time);
                $str_duration = str_pad($playbill_value['nns_time_len'],6,0,STR_PAD_LEFT);
                $temp_playbill_value['base_info'] = $playbill_value;
                $playbill_import_id = $this->get_video_cdn_import_id($this->get_c2_type(), $temp_playbill_value);
                $str_xml .='<Object ElementType="Schedule" ID="' . $playbill_import_id . '" Action="'. $action . '" Code="' . $playbill_import_id . '">';
                $str_xml .=   '<Property Name="ChannelCode">' . $live_import_id . '</Property>';
                $str_xml .=   '<Property Name="ChannelID">' . $live_import_id . '</Property>';
                $str_xml .=   '<Property Name="ProgramName"><![CDATA['.$playbill_value['nns_name'].']]></Property>';
                $str_xml .=   '<Property Name="StartDate">'.$str_start_date.'</Property>';
                $str_xml .=   '<Property Name="StartTime">' . $str_start_time . '</Property>';
                $str_xml .=   '<Property Name="Duration">' . $str_duration . '</Property>';
                $str_xml .=   '<Property Name="StorageDuration"></Property>';
                $str_xml .=   '<Property Name="Status">1</Property>';
                $str_xml .=   '<Property Name="CPContentID">'.$live_import_id.'</Property>';
                $str_xml .=   '<Property Name="Description"><![CDATA['.$playbill_value['nns_summary'].']]></Property>';
                $str_xml .=   '<Property Name="Genre"></Property>';
                $str_xml .='</Object>';
            }
        }
        else
        {
            $int_begin_time = strtotime($playbill_info['base_info']['nns_begin_time']);
            $str_start_date = date('Ymd', $int_begin_time);
            $str_start_time = date('His', $int_begin_time);
            $str_duration = str_pad($playbill_info['base_info']['nns_time_len'],6,0,STR_PAD_LEFT);
            $playbill_import_id = $this->get_video_cdn_import_id($this->get_c2_type(), $playbill_info);
            $str_xml .='<Object ElementType="Schedule" ID="' . $playbill_import_id . '" Action="'. $action . '" Code="' . $playbill_import_id . '">';
            $str_xml .=   '<Property Name="ChannelCode">' . $live_import_id . '</Property>';
            $str_xml .=   '<Property Name="ChannelID">' . $live_import_id . '</Property>';
            $str_xml .=   '<Property Name="ProgramName"><![CDATA['.$playbill_info['base_info']['nns_name'].']]></Property>';
            $str_xml .=   '<Property Name="StartDate">'.$str_start_date.'</Property>';
            $str_xml .=   '<Property Name="StartTime">' . $str_start_time . '</Property>';
            $str_xml .=   '<Property Name="Duration">' . $str_duration . '</Property>';
            $str_xml .=   '<Property Name="StorageDuration"></Property>';
            $str_xml .=   '<Property Name="Status">1</Property>';
            $str_xml .=   '<Property Name="CPContentID">'.$live_import_id.'</Property>';
            $str_xml .=    '<Property Name="Description"><![CDATA['.$playbill_info['base_info']['nns_summary'].']]></Property>';
            $str_xml .=   '<Property Name="Genre"></Property>';
            $str_xml .='</Object>';
        }
        $str_xml .=   '</Objects>';
        $str_xml .='</ADI>';
        /*******调用统一注入方法******/
        $execute_info = array(
            'nns_task_type' => "Schedule",
            'nns_action' => $action, //行为动作         DELETE
            'nns_content' => $str_xml,//注入XML内容
        );
        return $this->execute($execute_info);
    }

    private function epgfile()
    {
        if ($this->get_c2_info("action") === NS_CDS_DELETE)
        {
            return $this->do_destroy("DELETE", "epgfile");
        } else
        {
            $action = "REGIST-UPDATE";
        }
        $epg_file_set_info = $this->get_epg_file_set_info();
        $epg_file_info = $this->get_epg_file_info();

        if (empty($epg_file_set_info) || !is_array($epg_file_set_info))
        {
            return $this->write_log_return("C2任务epgfileset数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        if (empty($epg_file_info) || !is_array($epg_file_info))
        {
            return $this->write_log_return("C2任务epgfile数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }

        $show_time = (!isset($epg_file_set_info['nns_show_time']) || $epg_file_set_info['nns_show_time'] == '0000-00-00 00:00:00')
            ?  '' : date('YmdHis' , strtotime($epg_file_set_info['nns_show_time']));
        $xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
        $xml_str .= '<Objects>';
        $xml_str .= '<Object ElementType="EPGFileSet" ID="' . $epg_file_set_info['nns_import_id'] . '" >';
        $xml_str .= '<Property Name="EPGGroup">' . $epg_file_set_info['nns_group'] . '</Property>';//文件分组
        $xml_str .= '<Property Name="SystemFile">' . $epg_file_set_info['nns_system_file'] . '</Property>';//是否为系统文件，0否 1是；媒体文件URL,ftp://username:password@ip:port/...  标准FTP协议
        $xml_str .= '<Property Name="NeedUnTar">' . $epg_file_set_info['nns_tar']. '</Property>';//文件是否为tar包,0 否,1 是
        $xml_str .= '<Property Name="BeginTime">' . $show_time . '</Property>';//文件生效时间
        $xml_str .= '</Object>';
        foreach ($epg_file_info as $item)
        {
            $xml_str .= '<Object ElementType="EPGFile" ID="' . $item['nns_import_id'] . '" Action="' . $action .  '" >';
            $xml_str .= '<Property Name="SourceUrl">' . $item['nns_url'] . '</Property>';//模板文件URL,ftp://username:password@ip:port/...  标准FTP协议
            $xml_str .= '<Property Name="DestPath">' . $item['nns_dest_path'] . '</Property>';//厂商在EPG Sever 上存储该文件的相对路径。如果是相对路径的根路径，则用空表示。如：epg/bestv/
            $xml_str .= '<Property Name="MD5">' . $item['nns_md5'] . '</Property>';//文件生效时间
            $xml_str .= '</Object>';
        }
        $xml_str .= '</Objects>';
        $xml_str .= '<Mappings>';

        $xml_str .= '</ADI>';
        /*******调用统一注入方法******/
        $execute_info = array(
            'nns_task_type' => "EPGFile",
            'nns_action' => $action, //行为动作
            'nns_content' => $xml_str,//注入XML内容
        );
        return $this->execute($execute_info);
    }
    /**
     * 主媒资、分集、片源的删除
     * @param string $action
     * @param string $video_type
     * @return array
     */
    private function do_destroy($action = '', $video_type = "video")
    {
        if (!isset($action) && $this->get_c2_info("action") === NS_CDS_DELETE)
        {
            $action = "DELETE";
        }
        $action = isset($action) && strlen($action) > 0 ? strtoupper($action) : "DELETE";

        /*******获取CDN注入ID******/
        $cdn_import_id = $this->get_video_cdn_import_id($video_type);
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("C2任务生成CDN注入ID失败", NS_CDS_FAIL);
        }

        //映射节点类型
        switch ($video_type)
        {
            case "video" :
                $type = "Series";
                break;
            case "index" :
                $type = "Program";
                break;
            case "media" :
                $type = "Movie";
                break;
            default :
                $type = "Series";
                break;
        }

        $xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
        $xml_str .= '<Objects>';
        $xml_str .= '<Object ElementType="' . $type . '" ID="' . $cdn_import_id . '" Action="' . $action . '" Code="' . $cdn_import_id . '">';
        $xml_str .= '</Object>';
        $xml_str .= '</Objects>';
        $xml_str .= '</ADI>';
        /*******调用统一注入方法******/
        $execute_info = array(
            'nns_task_type' => $type,//删除操作的媒资类型，主媒资、分集、片源
            'nns_action' => $action, //行为动作
            'nns_content' => $xml_str,//注入XML内容
        );
        return $this->execute($execute_info);
    }


    /**
     * @description:对保存到本地的xml进行解析
     * @author:xinxin.deng
     * @date: 2018/3/6 10:36
     * @param $nns_notify_content
     * @return array
     */
    public function notify_content_to_arr($nns_notify_content)
    {
        \ns_core\m_load::load_np("np_xml2array.class.php");
        //解析下载的XML
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($nns_notify_content);
        $xml = $dom->saveXML();
        $xml_arr = \np_xml2array::getArrayData($xml);
        if ($xml_arr['ret'] != 1)
        {
            return $this->write_log_return("CDN消息反馈的xml解析失败：" . var_export($xml_arr, true), 1);
        }
        $xml_arr = (isset($xml_arr['data']['children'][0]['children'])) ? $xml_arr['data']['children'][0]['children'] : null;
        if (empty($xml_arr) || !is_array($xml_arr))
        {
            return $this->write_log_return('CDN消息反馈的xml解析成功，但是数组有问题:' . var_export($xml_arr, true), 1);
        }
        $result_notify = array();
        foreach ($xml_arr as $k => $v)
        {
            $result_notify[$v['attributes']['Name']] = $v['content'];
        }
        return \m_config::return_data(0, 'ok', $result_notify);
    }


    static public function get_BizDomain($sp_id)
    {
        if($sp_id=='hndx' || $sp_id=='hnlt_zx' || $sp_id=='hndx_hw')
        {
            return 520;
        }
        elseif($sp_id=='xjcbc_dx_hw' || $sp_id=='xjdx_hw' || $sp_id=='cbczq_hw' || $sp_id=='cqyx' || $sp_id=='cqyx_hw')
        {
            return 0;
        }
        elseif($sp_id=='xjcbc_dx_zte' || $sp_id=='xjdx_zte' || $sp_id=='cbczq_zte' )
        {
            return 257;
        }
        if ($sp_id == 'hljdx_hw')
        {
            return 0;
        }
        else
        {
            return 2;
        }
    }

}

